<template>
  <div>
    <van-nav-bar title="登录" />
    <!-- 表单内容 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="info.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="info.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          :loading="loading"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入index
import { loginAPI } from "@/api";
export default {
  data() {
    return {
      info: {
        mobile: "15387074502",
        code: "246810",
      },
      rules: {
        mobile: [
          { required: true, message: "请填写手机号" },
          { pattern: /^1[2-9]\d{9}$/, message: "请填写正确的手机号" },
        ],
        code: [
          { required: true, message: "请填写验证码" },
          { pattern: /^\d{6}$/, message: "请填写正确的验证码" },
        ],
      },
      loading: false,
    };
  },
  methods: {
    async onSubmit() {
      this.loading = true;
      //  发起数据请求
      try {
        let res = await loginAPI(this.info);
        // 把身份令牌保存到vuex中
        this.$store.commit("saveToken", res.data.data);
        // alert("登录成功");
        this.$toast.success("登录成功");
        // 判断用户是否有自己想访问的页面，有 就回到用户想访问的页面没有就默认跳转到主页
        if (this.$route.query.back) {
          // 有就是用户是在自己想访问的页面跳转到登录页的，登录成功后回到该页面
          this.$router.push(this.$route.query.back);
        } else {
          // 没有
          // 登录成功后跳转到首页
          this.$router.push("/layout/home");
        }
      } catch {
        // alert("账号或密码错误");
        this.$toast.fail("账号或密码错误");
      }
      this.loading = false;
    },
  },
};
</script>

<style>
</style>